<template>
  <div flex gap30px>
    <div class="flex-1 p-y-24px flex gap30px">
      <el-menu class="w240px !b-0" default-active="1" @select="clickMenu">
        <el-menu-item index="1">
          <span>全部</span>
        </el-menu-item>
        <el-menu-item index="2">
          <span>视频</span>
        </el-menu-item>
      </el-menu>

      <div
        v-if="videoList"
        class="flex-1 flex flex-col gap20px"
        v-infinite-scroll="loadMoreVideo"
        :infinite-scroll-disabled="loadDisabled"
        infinite-scroll-delay="400"
      >
        <div
          v-for="(video, index) in videoList"
          class="flex b-1px b-solid b-#e3e5e7 rd-8px p-[10px_20px] p-l-0"
        >
          <div
            class="w-48px h-48px bg-cover bg-center rd-full m-20px"
            :style="{
              backgroundImage: `url(${userStore.userInfo.userVo.avatar})`,
            }"
          ></div>
          <div flex-1>
            <div class="flex items-center justify-between">
              <div>
                <p class="text-17px leading-32px font-600">
                  {{ video.createByName }}
                </p>
                <p class="c-#9499a0 text-13px leading-28px">
                  {{
                    DateUtil.getTimeDiffDesc(
                      new Date(video.createTime),
                      new Date()
                    )
                  }}
                  · 投稿了视频
                </p>
              </div>
              <span
                @click="openDelVideoDialog(video.id, index)"
                class="iconfont icon-guanbi text-18px cursor-pointer"
              ></span>
            </div>

            <div flex>
              <div pos-relative>
                <video
                  :src="video.fileUrl"
                  class="w236px h-132px rounded-l-8px object-contain bg-#000 ___ cursor-pointer"
                  preload="none"
                  ref="videoPlayers"
                  @click="router.push({ path: `/video/${video.id}` })"
                  loop
                  muted
                  :poster="video.coverUrl"
                  @mouseenter="playVideo(index, videoPlayers)"
                  @mouseleave="pauseVideo(index, videoPlayers)"
                ></video>
                <div
                  v-if="isShowVideoTime"
                  class="absolute text-14px c-#fff bottom-0 right-0px p-b-6px p-r-6px"
                >
                  {{
                    DateUtil.convertSecondsToHMS(
                      Number(video.duration).toFixed(0)
                    )
                  }}
                </div>
              </div>
              <div
                class="h-132px b-1px b-solid b-#e3e5e7 b-l-0 rounded-r-8px flex-1 p-[16px_12px] box-border relative"
              >
                <p class="text-15px">{{ video.title }}</p>

                <div class="c-#9499a0 text-13px absolute bottom-0 p-b-5px">
                  <span class="iconfont icon-shipin m-r-4px v-mid"></span>
                  <span>{{ video.playCount }}</span>

                  <span
                    class="iconfont icon-danmushu m-l-20px m-r-4px v-mid"
                  ></span>
                  <span>{{ video.danmakuCount }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          v-if="loadingVideo"
          class="text-center m-t-20px text-14px c-#9499a0 cursor-default"
        >
          加载中...
        </div>
        <div
          v-if="loadDisabled"
          class="text-center m-t-20px text-14px c-#9499a0 cursor-default"
        >
          你已到达世界的尽头
        </div>
      </div>

      <div v-else class="flex justify-center items-center flex-1">
        <span class="iconfont icon-meiyoufenzu text-150px c-#999"></span>
      </div>
    </div>

    <!-- 侧边栏 -->
    <Sidebar />

    <!-- 删除视频弹框 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="删除动态会同时删除视频稿件"
      width="400"
      destroy-on-close
      align-center
      center
    >
      <p>视频删除后将无法恢复，请谨慎操作</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button
            :loading="delVideoBtnLoading"
            type="danger"
            @click="delVideo"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { type MenuItemClicked } from "element-plus";
import Sidebar from "../components/Sidebar.vue";
import {
  listVideoByMy as listVideoByMyApi,
  delVideo as delVideoApi,
} from "@/api/video";
import { onMounted, ref } from "vue";
import type { VideoQuery, VideoVO } from "@/api/video/types";
import { useUserStore } from "@/store/userStore";
import { DateUtil } from "@/utils/dateUtil";
import router from "@/router";

// 用户缓存信息
const userStore = useUserStore();

// 视频列表
const videoList = ref<VideoVO[]>([]);

// 视频ref对象
const videoPlayers = ref([]);

// 是否显示视频时长
const isShowVideoTime = ref(true);

// 删除视频弹窗
const centerDialogVisible = ref(false);

// 删除视频按钮Loading
const delVideoBtnLoading = ref(false);

// 待删除的视频id
const delVideoId = ref();

// 待删除的视频下标
const delVideoIndex = ref();

// 是否禁用无限滚动加载
const loadDisabled = ref(false);

// 加载video
const loadingVideo = ref(false);

const hasFirstLoad = ref(false);

// 视频列表查询参数
const videoQueryParam = ref<VideoQuery>({
  pageNum: 1,
  pageSize: 5,
});

const clickMenu = (
  index: string,
  indexPath: string[],
  item: MenuItemClicked
) => {
  console.log(index, item);
};

// 打开删除视频弹窗
const openDelVideoDialog = (videoId: number | string, index: number) => {
  delVideoId.value = videoId;
  delVideoIndex.value = index;
  centerDialogVisible.value = true;
};

// 删除视频
const delVideo = async () => {
  delVideoBtnLoading.value = true;
  await delVideoApi(delVideoId.value);
  videoList.value.splice(delVideoIndex.value, 1);
  centerDialogVisible.value = false;
  delVideoBtnLoading.value = false;
};

// 鼠标移入视频
const playVideo = async (index, videoPlayers) => {
  const video = videoPlayers[index];
  if (video) {
    try {
      isShowVideoTime.value = false;
      await video.play();
    } catch (err) {
      console.log("播放被阻止:", err);
    }
  }
};

// 鼠标移出视频
const pauseVideo = async (index, videoPlayers) => {
  const video = videoPlayers[index];
  if (video) {
    isShowVideoTime.value = true;
    await video.pause();
    // video.currentTime = 0; // 重置播放进度
  }
};

// 获取视频列表
const getMyVideoList = async () => {
  loadingVideo.value = true;
  let listVideoRes = await listVideoByMyApi(videoQueryParam.value);
  if (listVideoRes.rows) {
    videoList.value.push(...listVideoRes.rows);
  }
  loadingVideo.value = false;
  return listVideoRes.rows;
};

// 加载更多视频
const loadMoreVideo = async () => {
  if (loadingVideo.value || loadDisabled.value) return;

  // 首次 load，只让 v-infinite-scroll 触发一次
  if (!hasFirstLoad.value) {
    hasFirstLoad.value = true;
  } else {
    videoQueryParam.value.pageNum += 1;
  }

  const rows = await getMyVideoList();
  if (!rows?.length) {
    videoQueryParam.value.pageNum = Math.max(
      1,
      videoQueryParam.value.pageNum - 1
    );
    loadDisabled.value = true; // 没有更多数据了，禁用无限滚动加载
  }
};

// onMounted(async () => {
//   await getMyVideoList();
// });
</script>

<style scoped>
::v-deep(.el-menu-item.is-active) {
  background-color: #00aeec;
  border-radius: 8px;
  color: #fff;
}
::v-deep(.el-menu-item:hover) {
  border-radius: 8px;
}
::v-deep(.el-menu-item) {
  margin-top: 6px;
  margin-bottom: 6px;
}
</style>
